<?
/**
 * VoiceOne Settings/Extensions/edit
 *
 * Frontend to provide access to the extensions system in voiceone.
 * @package voiceone
 * @subpackage  settings_extensions
 * @todo Remove hardcoded italian message for confirmation box (AlertGood. AlertBad etc)
 */
 
  include ("../../../admin/config/cfg.php");
  global $cwlang;
  require_once("$absBasePath/lib/xajax/xajax.inc.php"); 
    sajax_init();
  //$sajax_debug_mode=true;
  
  //================ XAJAX ================
  function roll(){
    global $relBasePath,$cwlang;
    // Instantiate the xajaxResponse object
    $objResponse = new xajaxResponse();
    // Build response
    $html=" <img src=\"".$relBasePath."public/img/ico-progress.gif"."\" alt=\"loading\" /><span>".$cwlang["exten"]["loading"]."</span>";
    $objResponse->addAssign("loading","innerHTML",$html);
    // Return the xajaxResponse object
    return $objResponse->getXML(); 
  }
  function processFormData($formData){
    global $asterisk,$cwlang,$relBasePath;
    // Instantiate the xajaxResponse object
    $objResponse = new xajaxResponse();
    //extract form params
    $client=$formData["client"];
    $id=$client["id"];
    $exten=$client["extension"];
    $alias=$client["alias"];
    $password=$client["password"];
    $confirm=$client["confirm"];
    $voicemailOn=$client["voicemailOn"];
    $vpassword=$client["vpassword"];
    $vconfirm=$client["vconfirm"];
    $imgErr="<img src=\"".$relBasePath."/public/img/shutdown.png\" alt=\"error\">";
    //retrieve old exten and alias value
    if($id!=""){
      $ret=$asterisk->getClient($id,0);
      $v=$ret[0];
      $oldExen=$v["extension"];
      $oldAlias=$v["alias"];
    }
    // Check Extension ((no null)&&(numeric)&&(unique)&&( -neq Alias)
    $extensionErr=false;
    if($exten=="") { 
      //extension cannot be null
      $errOut[]= $cwlang["exten"]["extNoNull"];
      $objResponse->addAssign("extensionErr","innerHTML",$imgErr);
      $extensionErr=true;
    }else{
      //extension must be numeric
      for($i=0; $i<strlen($exten); $i++){ 
        $ch=ord($exten[$i]);
        if(!((($ch>47)&&($ch<58)))){
          $errOut[]= $cwlang["exten"]["extNumOnly"];
          $objResponse->addAssign("extensionErr","innerHTML",$imgErr);
          $extensionErr=true;
          break;
        }
      }
      //extension must be unique
      if(!(($id!="")and($exten==$oldExen))) {
        $ret=$asterisk->getExtension(0);
        if(is_array($ret)){
          foreach($ret as $e) {
            if($exten==$e["extension"]){
              $errOut[]= $cwlang["exten"]["extAlreadyExists"];
              $objResponse->addAssign("extensionErr","innerHTML",$imgErr);
              $extensionErr=true;
            }
          }
        }
      }
    }
    if($extensionErr===false) $objResponse->addAssign("extensionErr","innerHTML","");
    // Check Account Password ((no null)&&(==confirm)&&(alphanumeric))
    $passwordErr=false;
    if($password==""){
      //account password cannot be not null
      $errOut[]=$cwlang["exten"]["pwdnull"];
      $objResponse->addAssign("passwordErr","innerHTML",$imgErr);
      $passwordErr=true;
    }else if($password!=$confirm){
      //account password must be equal to confirm
      $errOut[]=$cwlang["exten"]["pwderr"];
      $objResponse->addAssign("passwordErr","innerHTML",$imgErr);
      $objResponse->addAssign("confirmErr","innerHTML",$imgErr);
      $passwordErr=true;
    }else{
      //account password must be alphanumeric
      for($i=0; $i<strlen($password); $i++){ 
        $ch=ord($password[$i]);
        if(!((($ch>96)&&($ch<123))||(($ch>64)&&($ch<91))||(($ch>47)&&($ch<58)))){
          $errOut[]=$cwlang["exten"]["extAlphaNumOnly"];
          $objResponse->addAssign("passwordErr","innerHTML",$imgErr);
          $passwordErr=true;
          break;
        }
      }
    }
    if($passwordErr===false){
      $objResponse->addAssign("passwordErr","innerHTML","");
      $objResponse->addAssign("confirmErr","innerHTML","");
    }
    // Check Alias ((alphanumeric)&&(unique))
    $aliasErr=false;

    if($alias!=""){
      //alias must be alphanumeric
      for($i=0; $i<strlen($alias); $i++){ 
        $ch=ord($alias[$i]);
        if(!((($ch>96)&&($ch<123))||(($ch>64)&&($ch<91))||(($ch>47)&&($ch<58)))) {
          $errOut[]=$cwlang["exten"]["aliasAlphaNumOnly"];
          $objResponse->addAssign("aliasErr","innerHTML",$imgErr);
          $aliasErr=true;
          break;
        }
      }
      //alias must be unique
      if(!(($id!="")and($alias==$oldAlias))) {
        $ret=$asterisk->getExtension(0,0);
        if(is_array($ret)){
          foreach($ret as $e){ 
            if($alias==$e["extension"]){
              $errOut[]=$cwlang["exten"]["aliasAlreadyExists"];
              $objResponse->addAssign("aliasErr","innerHTML",$imgErr);
              $aliasErr=true;
            }
          }
        }
      }
      //extension must be different from Alias
      if($alias==$exten){
        $errOut[]=$cwlang["exten"]["aliasEqualToExt"];
        $objResponse->addAssign("aliasErr","innerHTML",$imgErr);
        $aliasErr=true;
      }
    }
    if($aliasErr===false) $objResponse->addAssign("aliasErr","innerHTML","");

    // Check Voicemail Password ((no null)&&(==confirm)&&(numeric))
    if ($voicemailOn=="1") {
      $vpasswordErr=false;
      if($vpassword==""){
        //voicemail password must be not null
        $errOut[]=$cwlang["exten"]["vmPwdNoNull"]; 
        $objResponse->addAssign("vpasswordErr","innerHTML",$imgErr);
        $vpasswordErr=true;
      }else if($vpassword!=$vconfirm){
        //voicemail password must be equal to confirm
        $errOut[]=$cwlang["exten"]["vmPwdErr"];
        $objResponse->addAssign("vpasswordErr","innerHTML",$imgErr);
        $objResponse->addAssign("vconfirmErr","innerHTML",$imgErr);
        $vpasswordErr=true;
      }else{
        //voicemail password must be numeric
        for($i=0; $i<strlen($vpassword); $i++){ 
          $ch=ord($vpassword[$i]);
          if(!((($ch>47)&&($ch<58)))){
            $errOut[]=$cwlang["exten"]["vmPwdNumOnly"];
            $objResponse->addAssign("vpasswordErr","innerHTML",$imgErr);
            $vpasswordErr=true;
            break;
          }
        }
      }
    }
    if($vpasswordErr===false){
      $objResponse->addAssign("vpasswordErr","innerHTML","");
      $objResponse->addAssign("vconfirmErr","innerHTML","");
    }
    // Process Form
    if(isset($errOut)){
      $error="<div class=\"AlertBad\"><ul>";
      foreach($errOut as $err) $error.="<li>".$err."</li>";
      $error.="</ul></div>";
      $objResponse->addAssign("alert","innerHTML",$error);
      $objResponse->addAssign("loading","innerHTML","");
    }else{
      $group=$formData["group"];
      $technology=$formData["technology"];
      $entry=Array(
            "id" => $client["id"],
            "name" => $client["name"],
            "surname" => $client["surname"],
            "extension" => $client["extension"],
            "alias" => $client["alias"],
          //"username" => $client["username"],
            "password" => $client["password"],
            "language" => $client["language"],
            "groups" => $group, 
            "technology" => $technology
          );
      //add options to the entry
      foreach ($formData as $k=>$v) {
        if (substr($k,0,7)=="status_") {
          $k=substr($k,7);
          if ($v=="1") {
            $o["key"]=$k; 
            $o["value"]=$formData["option_".$k];
            $options[]=$o;
          }
        }
      }
      $entry["options"]=$options;
      //set voicemail
      if ($client["voicemailOn"]=="1") {
        $mailbox["mailbox"]=$client["extension"];
        $mailbox["password"]=$client["vpassword"];
        $mailbox["fullname"]=$client["name"]." ".$client["surname"];
        $mailbox["email"]=$client["email"];
        $mailbox["attach"]=$client["attach"];
        $mailbox["saycid"]=$client["saycid"];
        $mailbox["hidefromdir"]=$client["hidefromdir"];
        $entry["voicemail"]=$mailbox;
      }
      //put Client 
      $ret=$asterisk->putClient($entry);
      if ($ret>0) {
        $alert="<div class=\"AlertGood\">".$cwlang["exten"]["editSuccessfully"]."</div>";
        $_GET["id"]=$ret;
      }
      else $alert="<div class=\"AlertBad\">".$cwlang["exten"]["editFailed"]."</div>";
      //create session var $alert
      session_start();
      $_SESSION['alert']=$alert;
      $objResponse->addScript(" location.href = '../'; ");
      $objResponse->addAssign("loading","innerHTML",""); 
    }
    // Return the xajaxResponse object
    return $objResponse->getXML();  
  }
  $xajax = new xajax();
  $xajax->registerFunction("roll");
  $xajax->registerFunction("processFormData");
  $xajax->processRequests();
  
  //================ PAGE LOGIC ================
  //Get the client informations
  if (isset($_GET["id"]) and $_GET["id"]!="") {
    $id=$_GET["id"];
    $ret=$asterisk->getClient($id,0);
    if ($err=$asterisk->getError()) die("Error: $err");
    $v=$ret[0];
    $id=$v["id"];
    $name=$v["name"];
    $surname=$v["surname"];
    $extension=$v["extension"];
    $alias=$v["alias"];
    $username=$v["username"];
    $password=$v["password"];
    $language=$v["language"];
    $rule=$v["rule"];
    $technology=$v["technology"];
    $optionsArr=$v["options"];
    $groupsArr=$v["groups"];
    $voicemailArr=$v["voicemail"]; 
    //tech icon
    if ($technology==SIP) $prot="<img src=\"$relBasePath/public/img/sip.gif\" alt=\"sip\" />";
    if ($technology==IAX2) $prot="<img src=\"$relBasePath/public/img/iax.gif\" alt=\"iax\" />";
    //read the mailbox
    if (count($voicemailArr)>0) {
      $voicemailOn="1"; 
      $vpassword=$voicemailArr["password"];
      $email=$voicemailArr["email"];
      $attach=$voicemailArr["attach"];
      $saycid=$voicemailArr["saycid"];
      $hidefromdir=$voicemailArr["hidefromdir"];
    } else $voicemailOn="0";
    //title
    $title="Modify extension $extension &lt;$name $surname&gt;";
  } 
  else{
    //title
    $title="New Extension";
    unset($v);
  }
  //create the language list
  $availLang=getAvailLang();
  foreach($availLang as $l) {
    if ($l==$language or (!isset($language) and $l==$cwLanguage)) $s="selected=\"selected\""; else $s="";
    $langSelect.="<option value=\"$l\" $s>$l</option>\n";
  }
  //prepare the sidebar
  $retBuddy=$asterisk->getClient(0,0);
  if ($err=$asterisk->getError()) die("Error: $err");
  if (is_array($retBuddy))
  foreach ($retBuddy as $vBuddy) {
    $buddyid=$vBuddy["id"];
    $buddyExt=$vBuddy["extension"];
    $buddyName=$vBuddy["name"];
    $buddySurname=$vBuddy["surname"];
    $buddiesList.="<tr><td class=\"postit\">$buddyExt</td><td><a href=\"./?id=$buddyid\">$buddyName $buddySurname</a></td></tr>\n";
  }  
  //================ MAIN CONTENTS ================
  ob_start();
  $xajax->printJavascript("../../../admin/lib/xajax/"); ?>
  <div class="SectionHeader">
    <div id="loading" style="float: right;"></div>
    <h1><?=$title?></h1>
    <h3><a href="../" class="admin" ><?=$cwlang["exten"]["return"]?></a></h3>
  </div>
  <div id="alert"></div>
  <div id="basic_form">
    <form id="mainform" action="<?=$PHP_SELF?>" method="post">
      <table>
        <tr>
          <td>
            <p class="blockintro"><?=$cwlang["exten"]["personalinfo"]?></p>
            <div class="block">
              <dl>
                <dt class="required"><label for="client[name]"><?=$cwlang["exten"]["name"]?>:</label></dt>
                <dd><input type="text" size="25" maxlength="30" id="client[name]" name="client[name]" value="<?=$name?>" /><span id="nameErr"></span></dd>
                <dt class="required"><label for="client[surname]"><?=$cwlang["exten"]["surname"]?>:</label></dt>
                <dd><input type="text" size="25" maxlength="50" id="client[surname]" name="client[surname]" value="<?=$surname?>" /><span id="surnameErr"></span></dd>
                <dt class="required"><label for="client[extension]"><?=$cwlang["exten"]["exten"]?>:</label></dt>
                <dd><input type="text" size="25" maxlength="20" id="client[extension]" name="client[extension]" value="<?=$extension?>" onkeyup="document.getElementById('client[username]').value=this.value;"  onblur="document.getElementById('client[username]').value=this.value;" /><span id="extensionErr"></span></dd>
                <dt class="required"><label for="client[language]"><?=$cwlang["exten"]["language"]?>:</label></dt>
                <dd><select id="client[language]" name="client[language]"><?=$langSelect?></select></dd>
              </dl>
            </div>
          </td>
          <td>
            <p class="blockintro"><?=$cwlang["exten"]["authdata"]?></p>
            <div class="block">
              <dl>
                <dt class="required"><label for="client[username]"><?=$cwlang["exten"]["username"]?>:</label></dt>
                <dd><input type="text" size="25" maxlength="20" id="client[username]" name="client[username]" value="<?=$extension?>" disabled="disabled" /><span id="usernameErr"></span></dd>
                <dt class="required"><label for="client[password]"><?=$cwlang["exten"]["password"]?>:</label></dt>
                <dd><input type="password" size="25" maxlength="20" id="client[password]" name="client[password]" value="<?=$password?>" /><span id="passwordErr"></span></dd>
                <dt class="required"><label for="client[confirm]"><?=$cwlang["exten"]["confirm"]?>:</label></dt>
                <dd><input type="password" size="25" maxlength="20" id="client[confirm]" name="client[confirm]" value="<?=$password?>" /><span id="confirmErr"></span></dd>
                <dt class="required"><label for="client[alias]"><?=$cwlang["exten"]["alias"]?>:</label></dt>
                <dd><input type="text" size="25" maxlength="100" id="client[alias]" name="client[alias]" value="<?=$alias?>" /><span id="aliasErr"></span></dd>
              </dl>
            </div> 
          </td>
        </tr>
      </table>

<?    echo listOption($js, $technology, $optionsArr, false, true, RULE_OUTGOING, true);?>      
      
        <h2><?=$cwlang["exten"]["vmTitle"]?></h2>
      <p class="blockintro"><?=$cwlang["exten"]["vmDesc"]?></p>
      <div class="block">
        <dl>
          <dt class="required"><label for="client[voicemailOn]"><?=$cwlang["exten"]["vmFlag"]?>:</label></dt>
          <dd>
            <input type="radio" id="client[voicemailOn]" name="client[voicemailOn]" value="1" <?if ($voicemailOn==1) echo "checked=\"checked\""; ?> /> ON
            <input type="radio" id="client[voicemailOn]" name="client[voicemailOn]" value="0" <?if ($voicemailOn!=1) echo "checked=\"checked\""; ?> /> OFF
          </dd>
          <dt class="required"><label for="client[email]"><?=$cwlang["exten"]["email"]?>:</label></dt>
          <dd><input type="text" size="25" maxlength="100" id="client[email]" name="client[email]" value="<?=$email?>" /> <?=$cwlang["exten"]["vmEmailDesc"]?></dd>
          <dt class="required"><label for="client[vpassword]"><?=$cwlang["exten"]["password"]?>:</label></dt>
          <dd><input type="password" size="25" maxlength="20" id="client[vpassword]" name="client[vpassword]" value="<?=$vpassword?>" /><span id="vpasswordErr"></span> <?=$cwlang["exten"]["vmPwdDesc"]?></dd>
          <dt class="required"><label for="client[vconfirm]"><?=$cwlang["exten"]["confirm"]?>:</label></dt>
          <dd><input type="password" size="25" maxlength="20" id="client[vconfirm]" name="client[vconfirm]" value="<?=$vpassword?>" /><span id="vconfirmErr"></span> <?=$cwlang["exten"]["vmConfirmDesc"]?></dd>
          <dt class="required"><label for="client[attach]"><?=$cwlang["exten"]["vmAttachFlag"]?>:</label></dt>
          <dd><input type="checkbox" id="client[attach]" name="client[attach]" value="1" <?if ($attach==1) echo "checked=\"checked\""; ?> />
          <?=$cwlang["exten"]["vmAttachDesc"]?> </dd>
          <dt class="required"><label for="client[saycid]"><?=$cwlang["exten"]["vmCIDFlag"]?>:</label></dt>
          <dd><input type="checkbox" id="client[saycid]" name="client[saycid]" value="1" <?if ($saycid==1) echo "checked=\"checked\""; ?> />
          <?=$cwlang["exten"]["vmCIDDesc"]?></dd>
          <dt class="required"><label for="client[hidefromdir]"><?=$cwlang["exten"]["vmHideFlag"]?>:</label></dt>
          <dd><input type="checkbox" id="client[hidefromdir]" name="client[hidefromdir]" value="1" <?if ($hidefromdir==1) echo "checked=\"checked\""; ?> />
          <?=$cwlang["exten"]["vmHideDesc"]?></dd>
        </dl>
      </div>
        
<?    echo listGroup(GROUP_OF_EXTENSION, $js, $groupsArr);?>      
     
    <div class="action">
      <?if ($_GET["id"]!="") {?> <input type="hidden" id="client[id]" name="client[id]" value="<?=$id?>" /><?}?>
      <a href="#"><img src="<?=$relBasePath?>/public/img/<?=$cwLanguage?>/b-cancel.gif" alt="Cancel" onclick="location.href='../'; return false;"/>      
      <a href="#"><img src="<?=$relBasePath?>/public/img/<?=$cwLanguage?>/b-save.gif" alt="Save" onclick=" document.getElementById('alert').innerHTML=''; xajax_roll(); xajax_processFormData(xajax.getFormValues('mainform')); "/></a>
   <!--  
      <input type="image" src="<?=$relBasePath?>/public/img/<?=$cwLanguage?>/b-cancel.gif" alt="Cancel" onclick="location.href='../'; return false;"/>             
      <input type="image" src="<?=$relBasePath?>/public/img/<?=$cwLanguage?>/b-save.gif" alt="Save" onclick="return checkParam(document.getElementById('client[extension]').value, document.getElementById('client[alias]').value, document.getElementById('client[password]').value, document.getElementById('client[confirm]').value);"/>
    -->
    </div>
  </form>
 </div>   
 
  
  <?
  $contents=ob_get_contents();
  ob_end_clean();

  //================ SIDEBAR ================
  ob_start(); 
  ?>
    <div class="Sidebar">
      <h1><?=$cwlang["exten"]["otherExten"]?></h1>
      <p><?=$cwlang["exten"]["otherExtenDesc"]?></p>
      <table class="small">
        <?=$buddiesList?>
      </table>
    </div>
  <?  
  $sidebar=ob_get_contents();
  ob_end_clean();

  //================ SETTINGS ================
    sajax_handle_client_request();

  $smarty->assign("section", "extensions");
  $smarty->assign("subsection", "");
  $smarty->assign("templateType", "TwoColLeft");  //OneCol, TwoColLeft, TwoColRight
  $smarty->assign("contents", $contents);
  $smarty->assign("sidebar", $sidebar);
  $smarty->assign("ajax", $js);
  $smarty->display('settings.tpl');
?>

